#!/usr/bin/env python3
"""
羽毛球大赛分组摇号系统启动脚本
"""

import os
import sys
import subprocess
import json

def check_redis():
    """检查Redis是否运行"""
    try:
        import redis
        import json

        # 读取Redis配置
        with open('config.json', 'r', encoding='utf-8') as f:
            config = json.load(f)

        redis_config = {
            'host': config['redis']['host'],
            'port': config['redis']['port'],
            'db': config['redis']['db']
        }

        # 如果配置了密码，则添加密码参数
        if 'password' in config['redis'] and config['redis']['password']:
            redis_config['password'] = config['redis']['password']

        r = redis.Redis(**redis_config)
        r.ping()
        print("✓ Redis连接正常")
        return True
    except Exception as e:
        print(f"✗ Redis连接失败: {e}")
        print("请检查Redis服务是否启动，以及配置信息是否正确")
        return False

def install_dependencies():
    """安装Python依赖"""
    print("正在安装Python依赖...")
    try:
        subprocess.check_call([sys.executable, "-m", "pip", "install", "-r", "requirements.txt"])
        print("✓ 依赖安装完成")
        return True
    except subprocess.CalledProcessError as e:
        print(f"✗ 依赖安装失败: {e}")
        return False

def main():
    print("=" * 50)
    print("羽毛球大赛分组摇号系统")
    print("=" * 50)
    
    # 检查配置文件
    if not os.path.exists('config.json'):
        print("✗ 配置文件 config.json 不存在")
        return
    
    # 读取配置
    with open('config.json', 'r', encoding='utf-8') as f:
        config = json.load(f)
    
    print(f"总参与人数: {config['total_participants']}")
    print(f"分组: {', '.join(config['groups'])}")
    
    # 安装依赖
    if not install_dependencies():
        return
    
    # 检查Redis
    if not check_redis():
        print("\n请先启动Redis服务:")
        print("Windows: 下载并启动Redis")
        print("Linux/Mac: sudo systemctl start redis 或 redis-server")
        return
    
    print("\n启动Flask应用...")
    print("访问地址: http://localhost:5000")
    print("按 Ctrl+C 停止服务")
    print("-" * 50)
    
    # 启动Flask应用
    os.system("python app.py")

if __name__ == "__main__":
    main()
